import React from "react";
import moment from "moment";
import Calendar from "react-calendar";
import { DateCont, DateHead } from "./style";
import { activityInfo } from "../../api";
import { connect } from "react-redux";

class ClockDate extends React.PureComponent {
  weekZn = ["日", "一", "二", "三", "四", "五", "六"];
  constructor(props) {
    super(props);
    this.state = {
      date: new Date(),
      dateArr: [],
      info: ""
    };
  }

  componentDidMount() {
    activityInfo({
      id: this.props.match.params.id,
      mid: this.props.userInfo.id
    }).then(res => {
      let dates = res.data.data.member_records.map(item => {
        let d = item.created_at.split(" ")[0];
        return new Date(d);
      });
      this.setState({
        info: res.data.data,
        dateArr: dates
      });
    });
  }

  nowDay = () => {
    this.setState({
      date: new Date()
    });
  };
  onChange = value => {
    this.setState({ date: value.activeStartDate });
  };
  render() {
    let tileClassName = ({ date, view }) => {
      let getDate = moment(date).format("YYYY-MM-DD");
      for (const v of this.state.dateArr) {
        if (new Date(getDate).getTime() === v.getTime()) {
          return "atthis";
        }
      }
      return null;
    };
    let dyk = require("../../assets/icon_ydk.png");
    let zts = require("../../assets/icon_zts.png");
    return (
      <div>
        <DateHead>
          <div>
            <img src={dyk} width="40" alt="" />
            <p>已打卡</p>
            <p>{this.state.info && this.state.info.member_records.length}</p>
          </div>
          <div>
            <img src={zts} width="40" alt="" />
            <p>总天数</p>
            <p>{this.state.info.duration}</p>
          </div>
        </DateHead>
        <DateCont>
          <h2>
            <i className="iconfont">&#xe65f;</i>共{this.state.info.duration}天
            （{this.state.info && this.state.info.created_at.split(" ")[0]}~
            {this.state.info && this.state.info.close_time.split(" ")[0]}）
          </h2>
          <span onClick={this.nowDay.bind(this)}>今天</span>
          <Calendar
            prev2Label=""
            next2Label=""
            onActiveDateChange={this.onChange.bind(this)}
            value={this.state.date}
            tileClassName={tileClassName}
            formatShortWeekday={(locale, date) => {
              return this.weekZn[new Date(date).getDay()];
            }}
          />
        </DateCont>
      </div>
    );
  }
}

const mapStateToProps = state => ({
  userInfo: state.userInfo
});

export default connect(mapStateToProps)(ClockDate);
